from DateTime import DateTime
from Acquisition import aq_inner, aq_parent, aq_chain
from Products.CMFCore.utils import getToolByName
from Products.Five import BrowserView
from zope.i18n import translate
from zope.component import getMultiAdapter
from zope.viewlet.interfaces import IViewletManager

from Products.plonehrm import PloneHrmMessageFactory as _
from Products.plonehrm.browser.interfaces import IWorkLocationState
from Products.plonehrm.interfaces import IWorkLocation


class AbsenceOverview(BrowserView):
    """ Provides an overview of every absences in every worklocations.
    """

    def __call__(self):
        """ When calling the view, we compute 4 different things.
        - the average count of absences
        - the average percentage of days absent
        - the average total of absences
        - a dictionnary containing all data needed to be displayed.

        This dictionnary looks like this.

        {worklocation: {'rows': [rows generated by plonehrm.employees-absence],
                        'average_total': average total of absence for this WL,
                        'average_percentage': average percentage of absences for this WL,
                        'average_count': avserage count of absences for this worklocation}}
        """
        self.data = {}
        self.average_count = 0
        self.average_percentage = 0
        self.average_total = 0
        self.employees_total = 0
        
        # First, we find every worklocations.        
        worklocation_state = getMultiAdapter((self.context, self.request),
                                             name=u'worklocation_state')
        location_brains = worklocation_state.all_worklocations()

        
        for brain in location_brains:
            worklocation = brain.getObject()

            # Get the viewlet for this WL and computes data.
            viewlet = getMultiAdapter((worklocation, self.request, self),
                                      IViewletManager,
                                      name='plonehrm.employees-absence')
            viewlet.update()           

            for row in viewlet.rows:
                self.employees_total += 1
                self.average_count += row[-1]
                self.average_percentage += int(row[-2][:-1])
                self.average_total += row[-3]

            self.data[worklocation] = {'rows': viewlet.rows,
                                       'average_total': viewlet.average_total,
                                       'average_percentage': viewlet.average_percentage,
                                       'average_count': viewlet.average_count}

        if self.employees_total:
            self.average_count /= self.employees_total
            self.average_percentage /= self.employees_total
            self.average_total /= self.employees_total

        return self.index()
